<?php
namespace Home\Controller;

use Utuo\ForegroundController;

class FormController extends ForegroundController {
	
	public function _init() {
		layout(false);
		$this->setModelName("Site");
	}
	
	public function subListAction() {
		$id = I("id", 0, "intval"); // Form id
		$this->assign("id", $id);
		$this->display("Site/subList");
	}
	
	/**
	 * 提交表单数据列表
	 */
	public function dataListAction() {
		$openId = I('open_id', "");
		$page = $this->getPage();
		$pagesize = $this->getPageSize();
		$formId = I('id', 0, "intval");
		$dynaForm = M('DynaForm')->find($formId);
		$dynaForm and $dynaForm['config'] = unserialize($dynaForm["config"]);
		if(!empty($openId)) {
			$dynaFormDataLists = M("DynaFormData")->where("form_id=%d and open_id='%s'", $formId, $openId)->limit($pagesize)->order("id desc")->page($page)->select();
			foreach ($dynaFormDataLists as &$v) {
				$v['data'] = unserialize($v['data']);
				$v['data']['create_time'] = $v['create_time'];
			}
			$dynaForm['dataList'] = $dynaFormDataLists;
		}
		$this->assign("dynaForm", $dynaForm);
		$this->display("Site/dataList");
	}
	
	/**
	 * 表单显示
	 */
	public function showAction() {
		$id = I("id", 0, "intval"); // Form id
		$dynaForm = M("DynaForm")->find($id);
		$dynaForm and $dynaForm['config'] = unserialize($dynaForm['config']);
		$this->assign("dynaForm", $dynaForm);
		$this->display("Site/form");
	}
	
	/**
	 * 表单提交
	 */
	public function submitAction() {
		C("TOKEN_ON", true);
		$open_id = I('open_id', '');
		$m = M("DynaFormData");
		if( !$m->autoCheckToken($_POST) ) {
			$this->ajaxError("您已提交过了");
		}
		$id = I("id", 0, "intval"); // Form id
		$dynaForm = M("DynaForm")->find($id) or $this->ajaxError("表单不存在");
		$config = unserialize($dynaForm['config']);
		$submitData = array();
		foreach ($config as $k => $v) {
			$varVal = I($v['varName'], "");
			$submitData[$v['varName']] = $varVal;
		}
		false !== M("DynaFormData")->add(array(
			'open_id' => $open_id,
			'create_time' => time(),
			'form_id' => $id,
			'data' => serialize($submitData),
		)) and $this->ajaxSuccess(empty($dynaForm['result_msg'])?"提交成功":$dynaForm['result_msg']);
		$this->ajaxSuccess('提交失败');
	}
	
}